package cn.ai.boot.config;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class PCFParser {
    
    /**
     * 解析PCF文件并返回带行号的键值对集合
     * @param filePath 文件路径
     * @return 包含行号、键值对的PCFEntry对象列表
     */
    public static List<PCFEntry> parseWithLineNumbers(String filePath) throws IOException {
        List<PCFEntry> entries = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            int lineNumber = 1;
            while ((line = reader.readLine()) != null) {
                String trimmed = line.trim();
                if (!trimmed.isEmpty() && !trimmed.startsWith("#")) {
                    String[] parts = trimmed.split("\\s+", 2);
                    if (parts.length == 2) {
                        entries.add(new PCFEntry(
                            lineNumber, 
                            parts[0].trim(), 
                            parts[1].trim()
                        ));
                    }
                }
                lineNumber++;
            }
        }
        return entries;
    }

    /**
     * 转换为键值对映射（保留插入顺序）
     */
    public static Map<String, String> toOrderedMap(List<PCFEntry> entries) {
        Map<String, String> map = new LinkedHashMap<>();
        for (PCFEntry entry : entries) {
            map.put(entry.getKey(), entry.getValue());
        }
        return map;
    }

    /**
     * PCF条目数据封装类
     */
    public static class PCFEntry {
        private final int lineNumber;
        private final String key;
        private final String value;

        public PCFEntry(int lineNumber, String key, String value) {
            this.lineNumber = lineNumber;
            this.key = key;
            this.value = value;
        }

        public int getLineNumber() {
            return lineNumber;
        }

        public String getKey() {
            return key;
        }

        public String getValue() {
            return value;
        }

        @Override
        public String toString() {
            return String.format("[L%d] %s = %s", lineNumber, key, value);
        }
    }
}
